from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
import random


def get_random_color():
    return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))


def get_valid_code_img(request):
    img = Image.new("RGB", (270, 40), color=get_random_color())
    draw = ImageDraw.Draw(img)
    kumo_font = ImageFont.truetype("static/font/kumo.ttf", size=28)

    valid_code_str = ""
    for i in range(1):
        random_num = str(random.randint(0, 9))
        random_low_alhpa = chr(random.randint(95, 122))
        random_upper_alhpa = chr(random.randint(65, 90))
        random_char = random.choice([random_num, random_low_alhpa, random_upper_alhpa])
        draw.text((i * 40, 5), random_char, get_random_color(), font=kumo_font)
        # 保存验证码字符串
        valid_code_str += random_char

    request.session['valid_code_str'] = valid_code_str
    f = BytesIO()
    img.save(f, "png")
    data = f.getvalue()
    return data
